package com.iamteer.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.iamteer.dao.IAdminDao;
import com.iamteer.entity.Admin;

public class AdminDao_bak implements IAdminDao {
	
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";

	@Override
	public void save(Admin admin) {
		String sql = "INSERT INTO admin(userName,password) VALUES(?,?)";
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			//2 获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			//3 设置参数
			pstmt.setString(1, admin.getUsername());
			pstmt.setString(2, admin.getPassword());
			//4 执行更新
			pstmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}		
	}

	@Override
	public Admin findByNameAndPwd(Admin admin) {
		String sql = "SELECT * FROM admin WHERE userName=? AND password=?";
		Admin ad = null;
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			//2 获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			//3 设置参数
			pstmt.setString(1, admin.getUsername());
			pstmt.setString(2, admin.getPassword());
			//4 执行
			rs = pstmt.executeQuery();
			//5 获取结果
			if (rs.next()) {
				ad = new Admin();
				ad.setId(rs.getInt("id"));
				ad.setUsername(rs.getString("userName"));
				ad.setPassword(rs.getString("pwd"));
			}
			return ad;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public boolean userExists(String name) {
		String sql = "SELECT 1 FROM admin WHERE userName=?";
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			//2 获取 PreparedStatement 对象
			pstmt = con.prepareStatement(sql);
			//3 设置参数
			pstmt.setString(1, name);
			//4 执行
			rs = pstmt.executeQuery();
			if (rs.next()) {
				int id = rs.getInt(1);
				if (id > 0) {
					return true;
				}
			}
			return false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
				pstmt.close();
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}		
	}
}
